package org.com.db.core;

import java.util.List;

import org.com.db.api.ProduceComponet;
import org.com.db.domain.ProduceType;
import org.com.db.exception.DBException;
import org.com.db.exception.DBMSG;
import org.com.db.util.DBHelper;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ProduceComponetImpl implements ProduceComponet {
	private static final String TAG = ProduceComponetImpl.class.getName();
	private static DBHelper dbHelper;

	public ProduceComponetImpl(Activity activity) {
		dbHelper = new DBHelper(activity);
	}

	@Override
	public void addProduce(List<ProduceType> produces)throws DBException {
		
		final SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		try{	
			for (ProduceType p : produces) {
				final ContentValues cV = new ContentValues();
				cV.put("objectId",		 	p.getObjectId());
				cV.put("name", 				p.getName());
				cV.put("price",				p.getPrice());
				cV.put("pic", 				p.getPic());
				cV.put("describe",			p.getDescribe());
				
				db.insert("Produce", "", cV);
			}
		}catch(Exception e){
			Log.e(TAG, e.getMessage());
			throw new DBException(DBMSG.DB_ERROR001,e.getMessage());
		}finally{
			db.close();
		}
		

	}

	@Override
	public void removeProduce() throws DBException {
		final SQLiteDatabase db = dbHelper.getWritableDatabase();
		try{
			db.delete("Produce", null, new String[] {});
		}catch(Exception e){
			Log.e(TAG, e.getMessage());
			throw new DBException(DBMSG.DB_ERROR000,e.getMessage());
		}finally{
			db.close();
		}
		
	}

	@Override
	public void deleteThenInsert(List<ProduceType> produces) throws DBException {
		final SQLiteDatabase db = dbHelper.getWritableDatabase();
		try{
			
			//-刪除
			db.delete("Produce", null, new String[] {});
			
			//--新增
			for (ProduceType p : produces) {
				final ContentValues cV = new ContentValues();
				cV.put("objectId",		 	p.getObjectId());
				cV.put("name", 				p.getName());
				cV.put("price",				p.getPrice());
				cV.put("pic", 				p.getPic());
				cV.put("describe",			p.getDescribe());
				
				db.insert("Produce", "", cV);
			}
			
		}catch(Exception e){
			Log.e(TAG, e.getMessage());
			throw new DBException(DBMSG.DB_ERROR000,e.getMessage());
		}finally{
			db.close();
		}
	
		
	}
}
